﻿using System.ComponentModel.DataAnnotations;
using McMaster.Extensions.CommandLineUtils;

namespace Awesome.Examples.Example1;

[HelpOption("-h|--help", Description = "查看帮助")]
[Command(Name = "MyTool", Description = "这是一个命令行工具")]
public class Command
{
  private readonly string _version = "v1.0.0";


  [Option("-H|--host", Description = "主机")]
  public string Host { get; set; }


  /// <summary>
  ///  【验证】数据范围
  /// </summary>
  [Range(8000, 10000)]
  // [Argument(0, Description = "....")]
  [Option("-p|--port", Description = "端口(默认: 8080)", Inherited = true)]
  public int? Port { get; set; }


  /// <summary>
  /// 【验证】邮箱
  /// </summary>
  [EmailAddress]
  [Option("-e|--email", Description = "用户邮箱")]
  public string Email { get; }

  /// <summary>
  ///  【验证】文件是否存在 & 替换参数值
  /// </summary>
  [FileExists]
  [Option("-c|--config", ValueName = "config_file", Description = "配置文件")]
  public string Config { get; }


  /// <summary>
  /// 【验证】枚举参数 & 必选项
  /// </summary>
  // [Required(ErrorMessage = "type参数是必选项")]
  [McMaster.Extensions.CommandLineUtils.AllowedValues("server", "client", IgnoreCase = true)]
  [Option("-t|--type", Description = "服务类型")]
  public string Type { get; }

  /// <summary>
  ///  数组参数
  /// </summary>
  [Option(CommandOptionType.MultipleValue, ShortName = "P", LongName = "expose", Description = "开放的端口")]
  public string[] Expose { get; }

  /// <summary>
  /// 布尔参数
  /// </summary>
  [Option(CommandOptionType.NoValue, ShortName = "v", LongName = "version", Description = "版本信息")]
  public bool Version { get; }

  /// <summary>
  /// 不显示在帮助项中，仅用于调试 , 无简写
  /// </summary>
  [Option(CommandOptionType.NoValue, ShortName ="", Description = "调试", ShowInHelpText = false)]
  public bool Debug { get; set; }

  private void Init()
  {
    Host = string.IsNullOrEmpty(Host) ? "localhost" : Host;
    Port ??= 8080;
  }

  private void OnExecute(CommandLineApplication app, IConsole console)
  {
    try
    {
      if (Version)
      {
        console.WriteLine(_version);
        return;
      }

      Init();
      console.WriteLine($"服务地址：{Host}:{Port}");
      console.WriteLine($"开放的端口: {Expose.Join()}");
      console.WriteLine($"邮箱: {Email}");
      console.WriteLine($"配置文件: {Config}");
      // console.WriteLine($"环境状态: {_env.EnvironmentName}");
      console.WriteLine($"调试选项: {Debug}");
    }
    catch (Exception e)
    {
      Console.WriteLine(e.Message);
    }
  }

}
